﻿/*
 * @Author: ws.s 
 * @Date: 2021-12-17 15:06:23 
 * @Last Modified by: ws.s
 * @Last Modified time: 2021-12-17 15:06:47
 */
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


/// <summary>
/// UISlicedBar 组件，通过进度控制进度条的宽度
/// v1.0.1 修正 最小尺寸应该限制为显示，而不是直接隐藏掉进度
/// </summary>
[RequireComponent(typeof(RectTransform))]
[ExecuteInEditMode]
public class UISlicedProgressBar : MonoBehaviour
{
    public float maxWidth = 256;
    public float minWidthHide = 8f;

    [Range(0, 1f)]
    [SerializeField] private float _progress = 1f;

    private RectTransform rect;
    public float progress
    {
        get
        {
            return this._progress;
        }

        set
        {
            _progress = Mathf.Clamp(value, 0, 1f);
#if UNITY_EDITOR
            if (Application.isPlaying)
            {
                this.Refresh();
            }
            else
            {
                _flag = true;
            }
#else
            this.Refresh();
#endif
        }
    }

#if UNITY_EDITOR
    float size = 0;
    bool _flag = false;
    private void OnValidate()
    {
        if (rect == null) rect = GetComponent<RectTransform>();
        _flag = true;
    }
    // Update is called once per frame
    void Update()
    {
        if (_flag)
        {
            _flag = false;
            this.Refresh();
        }
    }
#endif

    private void Awake()
    {
        rect = GetComponent<RectTransform>();
        rect.pivot = new Vector2(0, 0.5f);
    }

    public void Refresh()
    {
        float size = this.maxWidth * _progress;
        if (size != 0 && size < minWidthHide) size = minWidthHide;
        if (this.rect == null)
        {
            return;
        }

        this.rect.sizeDelta = new Vector2(size, this.rect.sizeDelta.y);

    }




}
